package org.xiaojinlong.algo;

/**
 * @author Jin Long
 *         2016/6/27
 */
public class BinarySearch {
    public static int rank(int key, int[] a) {
        if (a == null) {
            throw new NullPointerException();
        }

        int lo = 0;
        int hi = a.length - 1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (key < a[mid]) {
                hi = mid - 1;
            } else if (key > a[mid]) {
                lo = mid + 1;
            } else {
                return mid;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        assert rank(3, null) == 2 : "二分查找有误！";
        int[] a = { 3, 5, 7, 9, 11, 12 };
        System.out.println(rank(7, a));
    }
}
